#include "opendb.h"
#include <QDebug>
#include <QMessageBox>

OpenDB::OpenDB(QObject *parent)
    : QObject{parent}
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
}

OpenDB &OpenDB::getInstance()
{
    static OpenDB instance;
    return instance;
}

void OpenDB::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("D:\\qtProject\\TcpServer\\cloud.db");
    if(m_db.open())
    {
        QSqlQuery query;
        query.exec("select * from userInfo");
        while(query.next())
        {
            QString data = QString("%1,%2,%3").arg(query.value(0).toString())
                               .arg(query.value(1).toString())
                               .arg(query.value(2).toString());
            qDebug()<<data;
        }
    }
    else
    {
        QMessageBox::critical(NULL, "打开数据库", "打开数据库失败");
    }
}

OpenDB::~OpenDB()
{
    m_db.close();
}

bool OpenDB::registHandle(const char *name, const char *pwd)
{
    if(name == NULL || pwd == NULL)
    {
        return false;
    }
    QString insert = QString("insert into userInfo(name,pwd) values(\'%1\',\'%2\')").arg(name).arg(pwd);
    QSqlQuery query;
    return query.exec(insert);

}

bool OpenDB::loginHandle(const char *name, const char *pwd)
{
    if(name == NULL || pwd == NULL)
    {
        return false;
    }
    QString insert = QString("select * from userInfo where name = \'%1\' and pwd = \'%2\' and online=0").arg(name).arg(pwd);
    QSqlQuery query;
    query.exec(insert);
    if( query.next())
    {
        QString update = QString("update userInfo set online=1 where name = \'%1\' and pwd = \'%2\' and online=0").arg(name).arg(pwd);
        return query.exec(update);
    }
    else
    {
        return false;
    }

}

void OpenDB::clientOffLine(const char *name)
{
    if(name == NULL)
    {
        qDebug()<<"name is null";
        return;
    }
    QString update = QString("update userInfo set online=0 where name = \'%1\'").arg(name);
    qDebug()<<update;
    QSqlQuery query;
    query.exec(update);
}
